<?php
!defined('IN_MUDDER') && exit('Access Denied');

define('MUDDER_CORE',   MUDDER_ROOT . 'core' . DS);
define('MUDDER_DATA',   MUDDER_ROOT . 'data' . DS);
define('MUDDER_CACHE',  MUDDER_DATA . 'cachefiles' . DS);
define('MUDDER_MODULE', MUDDER_CORE . 'modules' . DS);

// Get Global value
function _G() {
    global $_G;
    $max_level = 5;
    $result = '';
    $args_num = func_num_args();
    if($args_num > $max_level) return $result;
    $args = func_get_args();
    $val =& $_G;
    foreach ($args as $v) {
        if(!isset($val[$v])) return $result;
        $val =& $val[$v];
    }
    return $val;
}

/**
 * 在字符串中查找指定的字符
 * @return Boolean
 * */
function strposex($string, $find, $offset = 0) {
    return !(strpos($string, $find, $offset) === false);
}

//获取根路径
function get_urlroot() {
    $self = strtolower($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
    $url = str_replace('\\', '/', dirname($self));
    $url = str_replace('api', '', $url);
    if($url == '/' || $url == '\\') $url = '';
    return $url;
}

//数组格式化
function arrayeval($array, $level = 0) {
    if(!is_array($array)) {
        return "'".$array."'";
    }
    if(is_array($array) && function_exists('var_export')) {
        return var_export($array, true);
    }
    $space = '';
    for($i = 0; $i <= $level; $i++) {
        $space .= "\t";
    }
    $evaluate = "array (\n\r";
    $comma = $space;
    if(is_array($array)) {
        foreach($array as $key => $val) {
            $key = is_string($key) ? '\''.add_cs_lashes($key).'\'' : $key;
            $val = !is_array($val) && (!preg_match("/^\-?[0-9]\d*$/", $val) || strlen($val) > 12) ? '\''.add_cs_lashes($val, '\'\\').'\'' : $val;
            if(is_array($val)) {
                $evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
            } else {
                $evaluate .= "$comma$key => $val";
            }
            $comma = ",\n\r$space";
        }
    }
    $evaluate .= "\n\r$space)";
    return $evaluate;
}

//写入log
function log_write($file, $log) {
    $yearmonth = gmdate('Ym', _G('timestamp'));
    $logdir = MUDDER_DATA.'logs'.DS;
    $logfile = $logdir.$yearmonth.'_'.$file.'.php';
    if(@filesize($logfile) > 2048000) {
        $dir = opendir($logdir);
        $length = strlen($file);
        $maxid = $id = 0;
        while($entry = readdir($dir)) {
            if(strposex($entry, $yearmonth.'_'.$file)) {
                $id = intval(substr($entry, $length + 8, -4));
                $id > $maxid && $maxid = $id;
            }
        }
        closedir($dir);
        $logfilebak = $logdir.$yearmonth.'_'.$file.'_'.($maxid + 1).'.php';
        @rename($logfile, $logfilebak);
    }
    if($fp = @fopen($logfile, 'a')) {
        @flock($fp, 2);
        $log = is_array($log) ? $log : array($log);
        foreach($log as $tmp) {
            fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $tmp)."\n");
        }
        fclose($fp);
    }
}

//设置cookie
function set_cookie($var, $value, $life = 0, $prefix = 1) {
    $life = $life ? _G('timestamp') + $life : 0;
    $secure = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
    $var = ($prefix ? _G('cookiepre') : '') . $var;
    
    $r = setcookie($var, $value, $life, _G('cookiepath'), _G('cookiedomain'), $secure);
    return $r;
}

//删除cookie
function del_cookie($var, $prefix = 1) {
    if(is_array($var)) {
        foreach($var as $val) set_cookie($val, '', -360000, $prefix);
    } else {
        set_cookie($var, '', -360000, $prefix);
    }
}

//获取服务器信息
function get_webinfo() {
    $result = array();
    $result['self'] = strtolower($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
    $result['domain'] = strtolower($_SERVER['SERVER_NAME']);
    $result['agent'] = $_SERVER['HTTP_USER_AGENT'];
    $result['referer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    $result['scheme'] = $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $result['reuri'] = request_uri();
    $result['port'] = $_SERVER['SERVER_PORT'] == '80' ? '' : ':'.$_SERVER['SERVER_PORT'];
    $result['url'] = $result['scheme'] . $result['domain'] . $result['port'];
    return $result;
}
function request_uri()
{
    if (isset($_SERVER['REQUEST_URI'])) {
        $uri = $_SERVER['REQUEST_URI'];
    } else {
        if (isset($_SERVER['argv'])) {
            $uri = $_SERVER['PHP_SELF'] .(empty($_SERVER['argv'])?'':('?'. $_SERVER['argv'][0]));
        } else {
            $uri = $_SERVER['PHP_SELF'] .(empty($_SERVER['QUERY_STRING'])?'':('?'. $_SERVER['QUERY_STRING']));
        }
    }
    return $uri;
} 

//生成表单序列
function create_formhash($p1, $p2 = '', $p3 = '') {
    global $_G;
    $authkey = $_G['cfg']['authkey'];
    return md5($authkey . $p1 . $p2 . $p3);
}

//简单加密
function authcode($string, $operation = 'DECODE') {
    $string = $operation == 'DECODE' ? base64_decode($string) : base64_encode($string);
    return $string;
}

//简单加密
function authcode_ex($string, $operation = 'E') {
    global $_G;
    $key = $_G['cfg']['authkey'];
    $key = md5($key);
    $key_length = strlen($key);
    $string = $operation == 'D'?base64_decode($string):substr(md5($string.$key),0,8) . $string;
    $string_length = strlen($string);
    $rndkey = $box = array();
    $result = '';
    for($i=0; $i<=255; $i++) {
        $rndkey[$i]=ord($key[$i%$key_length]);
        $box[$i]=$i;
    }
    for($j=$i=0; $i<256; $i++) {
        $j=($j+$box[$i]+$rndkey[$i]) % 256;
        $tmp=$box[$i];
        $box[$i]=$box[$j];
        $box[$j]=$tmp;
    }
    for($a=$j=$i=0;$i<$string_length;$i++) {
        $a=($a+1)%256;
        $j=($j+$box[$a])%256;
        $tmp=$box[$a];
        $box[$a]=$box[$j];
        $box[$j]=$tmp;
        $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
    }
    if($operation == 'D') {
        if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)) {
            return substr($result,8);
        } else {
            return'';
        }
    } else {
        return str_replace('=','',base64_encode($result));
    }
}

//框架类自动加载
function fm_autoload($classname) 
{
    global $_G;
    if (class_exists($classname)) return true;

    $aps    = explode('_', $classname);
    $count  = count($aps);
    if ( ! $aps || $count <= 1) return false;

    //类的前缀
    $pre = trim($aps[0]);
    $aps = array_slice($aps, 1);
    
    if($pre == 'ms') {  //框架类库
        $filename = MUDDER_CORE.'lib'.DS.implode('_', $aps).'.php';
        if( ! is_file( $filename)) return false;
    } elseif ($pre == 'msm' || $pre == 'mc') { //模块模型和组件
        //文件夹
        $directory = $pre == 'msm' ? 'model' : 'component';

        //核心类库
        $filename_core = MUDDER_CORE.$directory.DS.implode('_', $aps).'_class.php';

        $module = $aps[0];
        $aps = array_slice($aps, 1);

        //现在各个模块里找
        $name = $aps ? implode('_', $aps) : $module;
        $filename = MUDDER_MODULE.$module.DS.$directory.DS.$name.'_class.php';
        if( ! is_file($filename)) {
            //最后在core/model里找
            if( ! is_file( $filename_core)) return false;
            $filename = $filename_core;
        }
    }

    //加载
    if($filename) {
        require_once($filename);
        //debug_log('file','autoload',$filename);
    }
    //通过检查是否存在这个类来判断是否有类加载
    return class_exists($classname);
}

spl_autoload_register( 'fm_autoload' );

/** end **/